package stock.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import stock.bean.CommonResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author BANGO
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    RestTemplate restTemplate;

    @RequestMapping("/add")
    public CommonResult<Object> add(){
        System.out.println("下单成功");
        // 在orde里面调用stock服务
        String msg = restTemplate.getForObject("http://stock-service/stock/reduce", String.class);
        return CommonResult.success("下单成功：" + msg);
    }

    private JSONObject getJsonObj(String str) throws UnsupportedEncodingException {
        JSONObject jsonObject = new JSONObject();
        str = URLDecoder.decode(str, "utf-8");
        str = str.replace("{", "").replace("}", "").trim();
        String[] split = str.split(",");
        if (split.length > 0){
            for (int i = 0; i < split.length; i++) {
                String paramsAndValueStr = split[i];
                String[] paramsAndValue = paramsAndValueStr.split("=");
                if (paramsAndValue.length == 2){
                    jsonObject.put(paramsAndValue[0].trim(),paramsAndValue[1].trim());
                }
            }
        }
        return jsonObject;
    }

    @RequestMapping("/submitOrder")
    @SentinelResource(value = "submitOrder")
    public CommonResult<Object> submitOrder(HttpServletRequest request) throws UnsupportedEncodingException {
        String userInfo = request.getHeader("userInfo");
        String userId = request.getHeader("userId");
        String username = request.getHeader("username");
        //转成对象
        JSONObject jsonObject = getJsonObj(userInfo);
        System.out.println("用户对象："  + jsonObject);
        System.out.println("userId信息："  + userId);
        System.out.println("username信息："  + username);
        System.out.println("创建时间 ："  + new Date(jsonObject.getLong("created")));

        initFlowRules();
        while (true) {
            // 1.5.0 版本开始可以直接利用 try-with-resources 特性
            Entry entry = null;
            try {
                entry = SphU.entry("HelloWorld");
                // 被保护的逻辑
                String msg = restTemplate.getForObject("http://stock-service/stock/reduce", String.class);
                System.out.println("下单成功：" + msg);
                return CommonResult.success("下单成功：" + msg);
            } catch (BlockException ex) {
                // 处理被流控的逻辑
                System.out.println("blocked!");
            }finally {
                if (entry != null){
                    entry.close();
                }
            }
        }
    }

    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("submitOrder");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(20);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

}

